// pages/my/myconsult/myconsult.js
Page({
  data: {
    consultData: [],
    pageNo: 1,
    pageSize: 6,
    userId: '',
    isLoading: false,
    hasMoreData: true,
    isRefreshing: false
  },

  switchTab(e) {
    const tab = e.currentTarget.dataset.tab;
    if (tab !== this.data.activeTab) {
      this.setData({ 
        activeTab: tab,
        consultData: [],
        pageNo: 1,
        hasMoreData: true
      }, () => {
        this.loadConsultData();
      });
    }
  },

  toggleComment(e) {
    const index = e.currentTarget.dataset.index;
    const consultData = this.data.consultData;
    consultData[index].isCommented = !consultData[index].isCommented;
    this.setData({ consultData });

    // 这里可以添加向后端发送评价状态更新的请求
    // 例如：
    // this.updateCommentStatus(consultData[index].id, consultData[index].isCommented);
  },

  onLoad() {
    this.setUserId();
    this.loadConsultData();
  },

  setUserId() {
    const userId = wx.getStorageSync('userId');
    if (!userId) {
      wx.showToast({
        title: '请先登录',
        icon: 'none',
        duration: 2000
      });
      setTimeout(() => {
        wx.navigateBack();
      }, 2000);
    } else {
      this.setData({ userId });
    }
  },

  loadConsultData() {
    if (this.data.isLoading || !this.data.hasMoreData) return;

    this.setData({ isLoading: true });

    wx.request({
      url: `http://localhost:8080/api/my/consult/getConsult1`,
      method: 'GET',

      data: {
        userId: this.data.userId,
        pageNo: this.data.pageNo,
        pageSize: this.data.pageSize
      },
      success: (res) => {

        console.log(res);
        if (res.statusCode === 200 && res.data.data) {
          const newData = res.data.data;
          if (newData.length > 0) {
            this.setData({
              consultData: [...this.data.consultData, ...newData],
              pageNo: this.data.pageNo + 1
            });
          } else {
            this.setData({ hasMoreData: false });
          }
        } else {

          wx.showToast({
            title: '加载失败，请重试',
            icon: 'none'
          });
        }
      },
      fail: (error) => {
        console.error('Request failed:', error);
        wx.showToast({
          title: '网络错误，请重试',
          icon: 'none'
        });
      },
      complete: () => {

        this.setData({ 
          isLoading: false,
          isRefreshing: false
        });
        wx.stopPullDownRefresh();

      }
    });
  },

  onReachBottom() {
    this.loadConsultData();
  },

  onPullDownRefresh() {
    this.setData({
      consultData: [],
      pageNo: 1,
      hasMoreData: true,
      isRefreshing: true
    });
    this.loadConsultData();
  },

  onRefresh() {
    this.onPullDownRefresh();
    this.setData({ isRefreshing: true });
    this.loadConsultData(true);
  },

  goToConsultDetail(e) {
    const consultId = e.currentTarget.dataset.id;
    wx.navigateTo({
      url: `/pages/consult/detail/detail?id=${consultId}`
    });

  }
});